package servlet;

import com.alibaba.fastjson.JSON;
import entity.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import service.IAdminService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class AdminServletMethods {
    private HttpServletResponse response;
    private HttpServletRequest request;
    private IAdminService service;

    public AdminServletMethods(HttpServletResponse response, HttpServletRequest request, IAdminService service) {
        this.response = response;
        this.request = request;
        this.service = service;
    }

    public void outLogin() {
        Cookie cookie = new Cookie("uid", "-1");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        String url = request.getContextPath();
        try {
            response.sendRedirect(url + "/admin/login.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void doRegister() {
        try {
            request.setCharacterEncoding("UTF-8");
            Map<String, String[]> paramaters = new HashMap<>(request.getParameterMap());
            paramaters.remove("method");
            User u = new User();
            BeanUtils.populate(u, paramaters);
            String responseString = service.doRegister(u);
            response.getWriter().print(responseString);
        } catch (UnsupportedEncodingException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void deleteUser() {
        int uid = Integer.parseInt(request.getParameter("uid"));
        String responseString = service.deleteUser(uid);
        try {
            response.getWriter().print(responseString);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void updateUser() {
        try {
            Map<String, String[]> paramaters = new HashMap<>(request.getParameterMap());
            paramaters.remove("method");
            User u = new User();
            BeanUtils.populate(u, paramaters);
            String reponseString = service.updateUserInfo(u);
            response.getWriter().write(reponseString);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getUserInfo() {
        Cookie[] cookies = request.getCookies();
        int uid = -1;
        if (cookies != null) {
            for (Cookie c : cookies) {
                if ("uid".equals(c.getName())) {
                    uid = Integer.parseInt(c.getValue());
                }
            }
        }
        String responseString = null;
        if (uid > 0) {
            responseString = service.getUserByUid(uid);
        } else {
            Msg msg = new Msg(404, "get failed");
            responseString = JSON.toJSONString(msg);
        }
        try {
            response.getWriter().print(responseString);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void doLogin() {
        /**
         *1.从前端拿到的数据构建User对象
         * 2.调用Dao层注册的方法
         */
        String username = request.getParameter("username");
        String password = request.getParameter("password");
//        System.out.println(username + " " + password);
        User admin = new User();
        admin.setUsername(username);
        admin.setPassword(password);
        int rs = service.doLogin(admin);
        String responseString = "{\"msg\":404}";
        if (rs > 0) {
            responseString = "{\"msg\":200}";
            Cookie cookie = new Cookie("uid", Integer.toString(rs));
            Cookie cookie1 = new Cookie("ad", Integer.toString(65535));
            cookie1.setPath("/");
            cookie1.setMaxAge(1000 * 60 * 24);
            cookie.setMaxAge(1000 * 60 * 24);
            cookie.setPath("/");
            response.addCookie(cookie);
            response.addCookie(cookie1);
        }
        try {
            response.getWriter().print(responseString);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getUser() {
        String responseString = service.getUser();
        try {
            response.getWriter().print(responseString);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getDefault() {
        try {
            Msg msg = new Msg(404, "接口错误或权限越界!=>也可能是你没有重启服务器哦<=");
            response.getWriter().print(JSON.toJSONString(msg));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void getHome() {
        String date = service.getAdminHome();
        try {
            response.getWriter().print(date);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getProduct() {
        String data = service.getProduct();
        try {
            response.getWriter().print(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void updateProduct() {
        try {
            // 将前端传来的参数封装到一个新的 Map 对象中 (request中的Map无法修改, 而我们需要移除"method"参数)
            Map<String, String[]> arg = new HashMap<>(request.getParameterMap());
            // 移除 "method" 参数
            arg.remove("method");
            // 准备一个 Product对象用来封装信息
            Product product = new Product();
            // 封装信息
            BeanUtils.populate(product, arg);
            // 调用Service层方法, 获得数据
            String data = service.updateProduct(product);
            // 将数据写回
            response.getWriter().print(data);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void deleteProduct() {
        try {
            // 获得前端传来的 pid
            int pid = Integer.parseInt(request.getParameter("pid"));
            // 调用Service层方法, 获得数据
            String data = service.deleteProduct(pid);
            // 将数据写回
            response.getWriter().print(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void addProduct() {
        // 基本步骤和 updateProduct() 差不多
        try {
            // 将前端传来的参数封装到一个新的 Map 对象中 (request中的Map无法修改, 而我们需要移除"method"参数)
            Map<String, String[]> arg = new HashMap<>(request.getParameterMap());
            // 移除 "method" 参数
            arg.remove("method");
            // 准备一个 Product对象用来封装信息
            Product product = new Product();
            // 封装信息
            BeanUtils.populate(product, arg);
            // 调用Service层方法, 获得数据
            String data = service.addProduct(product);
            // 将数据写回
            response.getWriter().print(data);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getProductnote() {
        //调用业务层方法
        String data = service.getProductnote();
        try {
            //返回业务层转换得来的json数据
            response.getWriter().print(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void deleteProductnote() {

        try {
            // 获得前端传来的 pnid
            int pnid = Integer.parseInt(request.getParameter("pnid"));
            // 调用Service层方法, 获得数据
            String data = service.deleteProductnote(pnid);
            // 将数据写回
            response.getWriter().print(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void addProductnote() {
        // 基本步骤和 updateProduct() 差不多
        try {
            // 将前端传来的参数封装到一个新的 Map 对象中 (request中的Map无法修改, 而我们需要移除"method"参数)
            Map<String, String[]> arg = new HashMap<>(request.getParameterMap());
            // 移除 "method" 参数
            arg.remove("method");
            // 准备一个 Product对象用来封装信息
            ProductNote productnote = new ProductNote();
            // 封装信息(这里无法封装，日期需要转换)
            DateConverter converter = new DateConverter();
            converter.setPattern(new String("yyyy-MM-dd"));
            ConvertUtils.register(converter, Date.class);
            BeanUtils.populate(productnote, arg);
            // 调用Service层方法, 获得数据
            String data = service.addProductnote(productnote);
            // 将数据写回
            response.getWriter().print(data);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void updateProductnote() {
        try {
            // 将前端传来的参数封装到一个新的 Map 对象中 (request中的Map无法修改, 而我们需要移除"method"参数)
            Map<String, String[]> arg = new HashMap<>(request.getParameterMap());
            // 移除 "method" 参数
            arg.remove("method");
            // 准备一个 Product对象用来封装信息
            ProductNote productNote = new ProductNote();
            // 封装信息
            BeanUtils.populate(productNote, arg);
            // 调用Service层方法, 获得数据
            String data = service.updateProductnote(productNote);
            // 将数据写回
            response.getWriter().print(data);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void addPurchasedProduct(){
        try {
            Map<String, String[]> arg = new HashMap<>(request.getParameterMap());
            // 移除 "method" 参数
            arg.remove("method");
            // 准备一个 Product对象用来封装信息
            PurchasedProduct purchasedProduct = new PurchasedProduct();
            // 封装信息
            BeanUtils.populate(purchasedProduct, arg);
            // 调用Service层方法, 获得数据
            String data = service.addPurchaseProduct(purchasedProduct);
            // 将数据写回
            response.getWriter().print(data);
        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void deletPurchasedProduct() {
        try {
            // 获得前端传来的 ppid
            int ppid = Integer.parseInt(request.getParameter("ppid"));
            // 调用Service层方法, 获得数据
            String data = service.deletePurchaseProduct(ppid);
            // 将数据写回
            response.getWriter().print(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getPurchasedProduct() {
        String data = service.getPurchasedProduct();
        try {
            response.getWriter().print(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
